import struct
import sys

def analyze_binary_once(data, start_pos):
    while True:
        # 查找到0x55, 0x55出现的位置
        found_pos = data[start_pos:].find(b'\x55\x55')
        if found_pos == -1:
            # print("0x55, 0x55 not found in remaining data")
            return None, -1

        # 获得0x55, 0x55之前两个字节
        pre_pos = start_pos + found_pos - 2
        if pre_pos >= 0:  # 防止出现负索引
            pre_bytes = data[pre_pos:pre_pos+2]
            if len(pre_bytes) != 2:
                print("Not enough bytes for a uint16 at preposition", pre_pos)
                return None, -1

            pre_uint16_val = struct.unpack("<H", pre_bytes)[0]  # "<H" 表示小端模式的 unsigned short
            if pre_uint16_val == 0:  # 如果前两个字节组成的unsigned short等于0，则跳过
                start_pos += found_pos + 2  # 更新起始位置，继续查找下一个0x55, 0x55
                continue

        # 找到了符合条件的0x55, 0x55，开始解析数据
        start_pos += found_pos
        break

    results = []
    for i in range(18):
        # 计算uint16的开始和结束位置
        start = start_pos + 6 + i*6
        end = start + 2

        # 读取并解析uint16
        uint16_bytes = data[start:end]
        if len(uint16_bytes) != 2:
            print("Not enough bytes for a uint16 at position", i)
            break

        uint16_val = struct.unpack("<H", uint16_bytes)[0]  # "<H" 表示小端模式的 unsigned short
        results.append((i+1, uint16_val))

    results = f"self.moves({str(results)}, {str(pre_uint16_val)})"
    return results, end + 2 + 6

def analyze_binary_file(filename):
    # 读取二进制文件
    with open(filename, "rb") as f:
        data = f.read()

    start_pos = 0
    all_results = []

    # 循环查找直到文件结束
    while start_pos < len(data):
        results, start_pos = analyze_binary_once(data, start_pos)
        if results == None or len(results) == 0: # 没有找到更多的0x55, 0x55
            break
        print(results)

    return all_results


#从args获得文件名
if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python parse.py <filename>")
        exit(1)

    filename = sys.argv[1]
    analyze_binary_file(filename)
